<template>
  <div class="main">
    <h3>欢迎登陆</h3>
    <div style="width: 30%;">
      <el-form ref="form" :model="form" size="normal" :rules="rules">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user-solid" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" show-password v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%;" type="primary" @click="login">登陆</el-button>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%;" type="primary" @click="this.$router.push('/register')">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "Login",
  data() {
    return {
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
      },
      form: {}
    }
  },
  methods: {
    // 登陆
    login() {
      // 通过验证才发送请求
      this.$refs['form'].validate((valid) => {
        if (valid) {
          request.post("api/user/login", this.form).then(res => {
            if (res.code === '0') {
              this.$message({
                type: "success",
                message: "登陆成功"
              })
              // 保存用户信息到本地
              sessionStorage.setItem("user", JSON.stringify(res.data))
              // 登陆成功就跳转到主页
              this.$router.push("/")
            } else {
              this.$message({
                type: "error",
                message: res.msg
              })
            }
          })
        }
      })


    }
  }
}
</script>

<style scoped>
.main {
  width: 100%;
  min-height: 100vh;
  background-color: darkslateblue;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.main h3 {
  color: #cccccc;
  font-weight: bolder;
  padding: 2rem;
}
</style>